package com.study.mike.controller;

import cn.hutool.json.JSONUtil;
import com.study.mike.model.dto.ParamDTO;
import com.study.mike.service.RetryService;
import io.lettuce.core.dynamic.annotation.Param;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Random;

/**
 * @author kh
 */
@RestController
public class TestController {
    @Resource
    private RetryService retryService;

    @GetMapping("/ajax")
    public ModelAndView test() {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("/user/login");
        return modelAndView;
    }

    //SpringBoot接收ajax请求的方式
    //方式一：使用HttpServletRequest request接收请求参数
    @GetMapping("/getCode")
    @ResponseBody
    public String getCode(HttpServletRequest request) {
        HttpSession session = request.getSession(true);
        String id = request.getParameter("id");
        System.out.println("AJAX传递的参数：" + id);
        //获取5位验证码
        return randomCodes();
    }

    //方式二：用@Param映射单个值
    @GetMapping("/getCode1")
    @ResponseBody
    public String getCode1(@Param("id") Integer id) {
        System.out.println(id);
        //获取5位验证码
        return randomCodes();
    }

    public String randomCodes() {
        String str = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
        StringBuilder code = new StringBuilder(5);
        for (int i = 0; i < 5; i++) {
            char ch = str.charAt(new Random().nextInt(str.length()));
            code.append(ch);
        }
        return code.toString();
    }

    /**
     * 测试赋值
     * @param str
     * @return
     */
    @PostMapping("/param")
    public ParamDTO testParam(@RequestBody String str) {
        ParamDTO paramDTO = JSONUtil.toBean(str,ParamDTO.class);
        System.out.println(paramDTO);
        return paramDTO;
    }

    /**
     * 重试机制
     */
    @PostMapping("/retry")
    public void testRetry(){
        retryService.retryTransferAccounts(1);
    }
}
